#! /usr/bin/env python

# -*- coding: UTF-8 -*-
# ==============================================================================
# Filename : MiniMap.py
# Purpose  :
# Author   : Yohann Li (lyh001686@sina.com)
# Date     : 2020-07-01 17:10
# ==============================================================================
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QFont, QTextCursor
from PyQt5.QtWidgets import QPlainTextEdit

from Widgets.Highlighter2 import Highlighter
from Widgets.ScrollBar import ScrollBar
from conf.configuration import logger


class MiniMap(QPlainTextEdit):
    barv_pySignal = pyqtSignal(tuple)
    finding_state_pySignal = pyqtSignal(bool)

    def __init__(self, name: str = '', *args, **kwargs):
        super(MiniMap, self).__init__(*args, **kwargs)
        _width = 100
        self.setFixedWidth(_width)
        # self.setReadOnly(True)
        self.setObjectName(name + '_minimap')
        self.setTabStopWidth(4)
        self.set_font()
        self.sBar = ScrollBar(self)
        self.setVerticalScrollBar(self.sBar)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setStyleSheet("""QScrollBar:vertical{width:%dpx;background:rgba(222, 222,222,100)}
        QScrollBar::handle:vertical{width:%dpx;height:300px!important; background:rgba(222, 222,222, 200)}""" % (100, 100))
        self.setLineWrapMode(QPlainTextEdit.NoWrap)
        # self.setLineWrapMode(QTextEdit.NoWrap)
        self.highlighter = Highlighter(self.document(), True)
        # self.installEventFilter(self)
        # self.selectionChanged.connect(self._highlight)
        self.finding_state_pySignal.connect(self._highlight)

    def _highlight(self, v: bool):
        self.setProperty('find_state', 1 if v else 0)
        self.style().polish(self)

    def insert_at_end(self, text: str):
        self.moveCursor(QTextCursor.End, QTextCursor.MoveAnchor)
        self.insertPlainText(text)

    def insert(self, text: str):
        # logger.debug(repr(text))
        self.insertPlainText(text)

    # def eventFilter(self, a0: QObject, a1: QEvent) -> bool:
    #     if type(a0) == QScrollBar and a1.type() in [5, 31]:
    #         v = a0.value()
    #         max = self.verticalScrollBar().maximum()
    #         if v and max > 0:
    #             self.barv_pySignal.emit((v, max))
    #     return super(MiniMap, self).eventFilter(a0, a1)

    def set_font(self):
        logger.debug(f'minimap changed, setting font')
        # font = QFont('Arial')
        font = QFont()
        font.setFixedPitch(True)
        font.setPointSize(2)

        self.setFont(font)
